package com.meltingslime.asciifight;

import org.fusesource.jansi.AnsiConsole;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Calendar;
import java.text.SimpleDateFormat;

/**
 * Author: LucaFraga
 * Date: 01/01/13 12.25
 */
public class Logger {
    private static Calendar _calendar = Calendar.getInstance();
    private static SimpleDateFormat _sdf = new SimpleDateFormat("yy/MM/dd hh:mm:ss");
    private FileWriter _file;
    private boolean _isFileLog;
    private BufferedWriter _stream;
    public LogTypes MinimumLog = LogTypes.All;
    public  enum LogTypes{
        Normal(0),
        Warning(1),
        Error(2),
        Severe(3),
        Fatal(4),
        All(-1);
        private final int id;
        LogTypes(int id)
        {
            this.id = id;
        }
        @Override
        public String toString()
        {
            return errorPrefixDict.get(this);
        }
    }


    public static Map<LogTypes, String> errorPrefixDict = new HashMap<LogTypes, String>();
    public Logger()
    {
        errorPrefixDict.put(LogTypes.Normal, "[LOG] (%s) ");
        errorPrefixDict.put(LogTypes.Warning, "[WRN] (%s) ");
        errorPrefixDict.put(LogTypes.Error,"[ERR] (%s) " );
        errorPrefixDict.put(LogTypes.Severe, "[SEV] (%s) " );
        errorPrefixDict.put(LogTypes.Fatal, "[FTL] (%s) " );
    }
    public Logger(String fileName)
    {
        this();
        try {
            _file = new FileWriter(fileName, false);
        } catch (IOException e) {
            AnsiConsole.out.println(String.format("FATAL: Cannot open log file at %s",fileName));
            System.exit(0);
        }
        _stream = new BufferedWriter(_file);
        _isFileLog = true;
    }
    public void WriteLine(String log, LogTypes type)
    {
        Write(log+"\r\n", type);
    }
    public void WriteLine(String log)
    {
        WriteLine(log, LogTypes.Normal);
    }
    public void Write(String log, LogTypes type)
    {
        String timeStamp =   _sdf.format(_calendar.getTime());
        String buffer = String.format(type.toString(), timeStamp);
        buffer += log;
        if(_isFileLog)
        { try {
            _stream.write(buffer);
            _stream.flush();
        } catch (IOException e) {
            AnsiConsole.out.println("FATAL: Cannot access to log file.");
            System.exit(0);
        }
        }
        if(type.id >= MinimumLog.id)
        {
            AnsiConsole.out.print(buffer);
        }
    }
    public void Write(String log)
    {
        Write(log, LogTypes.Normal);
    }



}
